package com.xoa.service.party;


import com.xoa.dao.party.EnOpenHoleMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.EnOpenHole;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 开墙打洞信息表
 * Created by gsb on 2018/1/6.
 */
@Service
public class EnOpenHoleService {

    @Resource
    private EnOpenHoleMapper enOpenHoleMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午11:36:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> insertSelective(EnOpenHole enOpenHole, HttpServletRequest request, String gridLocation){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            if(gridLocation!=null){
                enOpenHole.setS1(gridLocation);
            }
            enOpenHole.setCreateUser(user.getUserId());
            enOpenHole.setCreateTime(DateFormat.getDatestr(new Date()));
            enOpenHoleMapper.insertSelective(enOpenHole);
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午11:40:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> deleteByPrimaryKey(Integer oid){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            enOpenHoleMapper.deleteByPrimaryKey(oid);
            json.setMsg("ok");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 上午11:40:51
     * 类介绍  :   修改
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> updateByPrimaryKeySelective(EnOpenHole enOpenHole, HttpServletRequest request, String gridLocation){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            if(gridLocation!=null){
                enOpenHole.setS1(gridLocation);
            }
            enOpenHoleMapper.updateByPrimaryKeySelective(enOpenHole);
            json.setMsg("ok");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }



    public ToJson<EnOpenHole> selectByList(EnOpenHole enOpenHole, Integer page, Integer pageSize,
                                           boolean useFlag, HttpServletRequest request, HttpServletResponse response) {
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if (useFlag) {
                map.put("page", pageParams);
            }
            map.put("s1", enOpenHole.getS1());

            List<EnOpenHole> enOpenHoleList = enOpenHoleMapper.selectByList(map);

            String jutiAddress=mapOwnerinfoMapper.selectByLabelName(enOpenHole.getS1());
            enOpenHoleList.get(0).setJutiAddress(jutiAddress);

            if (enOpenHoleList != null && enOpenHoleList.size() > 0) {
                for (EnOpenHole enOpenHole1 : enOpenHoleList) {
                    if ("1".equals(enOpenHole1.getComform())) {
                        enOpenHole1.setComform("有");
                    } else if ("0".equals(enOpenHole1.getComform())) {
                        enOpenHole1.setComform("无");
                    } else {
                        enOpenHole1.setComform("");
                    }
                    if ("1".equals(enOpenHole1.getMakeHole())) {
                        enOpenHole1.setMakeHole("是");
                    } else if ("0".equals(enOpenHole1.getMakeHole())) {
                        enOpenHole1.setMakeHole("否");
                    } else {
                        enOpenHole1.setMakeHole("");
                    }
                    if ("1".equals(enOpenHole1.getHoleDisposalResult())) {
                        enOpenHole1.setHoleDisposalResult("房屋拆迁");
                    } else if ("2".equals(enOpenHole1.getHoleDisposalResult())) {
                        enOpenHole1.setHoleDisposalResult("恢复原状");
                    } else {
                        enOpenHole1.setHoleDisposalResult("");
                    }
                }
            }
            json.setObj(enOpenHoleList);
            json.setTotleNum(enOpenHoleMapper.selectCount(enOpenHole));
            json.setFlag(0);
            json.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 下午13:20:51
     * 类介绍  :   详情
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> selectById(Integer oid){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            EnOpenHole enOpenHole = enOpenHoleMapper.selectById(oid);
            json.setObject(enOpenHole);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }

    public ToJson<EnOpenHole> queryByList(){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {

            List<EnOpenHole> enOpenHoles = enOpenHoleMapper.queryByList();

            json.setObject(enOpenHoles);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }


    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 下午13:25:51
     * 类介绍  :   列表  或 导出 也可条件查询
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> queryList(EnOpenHole enOpenHole, Integer page, Integer pageSize,
                                        boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export){
        ToJson<EnOpenHole> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enOpenHole",enOpenHole);
            if(export==null){
                export="0";
            }
            List<EnOpenHole> enOpenHoleList = enOpenHoleMapper.selectList(map);
            if (enOpenHoleList!=null&&enOpenHoleList.size()>0){
                for (EnOpenHole enOpenHole1:enOpenHoleList){
                    if ("1".equals(enOpenHole1.getComform())){
                        enOpenHole1.setComform("有");
                    }else if ("0".equals(enOpenHole1.getComform())){
                        enOpenHole1.setComform("无");
                    }else {
                        enOpenHole1.setComform("");
                    }
                    if ("1".equals(enOpenHole1.getMakeHole())){
                        enOpenHole1.setMakeHole("是");
                    }else if ("0".equals(enOpenHole1.getMakeHole())){
                        enOpenHole1.setMakeHole("否");
                    }else {
                        enOpenHole1.setMakeHole("");
                    }
                    if ("1".equals(enOpenHole1.getHoleDisposalResult())){
                        enOpenHole1.setHoleDisposalResult("房屋拆迁");
                    }else if ("2".equals(enOpenHole1.getHoleDisposalResult())){
                        enOpenHole1.setHoleDisposalResult("恢复原状");
                    }else {
                        enOpenHole1.setHoleDisposalResult("");
                    }
                }
            }
            json.setObj(enOpenHoleList);
            json.setTotleNum(enOpenHoleMapper.selectCount(enOpenHole));
            json.setFlag(0);
            json.setMsg("ok");
            if (export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("开墙打洞信息导出", 11);
                String[] secondTitles = {"是否符合“三有六无”", "台账编号", "详细地址", "行政区", "街乡镇", "社区村","所属街路",
                        "具体街道号码","是否开墙打洞","开墙打洞处置结果","牌匾内容"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"comform", "parameterNum", "detailAddress", "district",
                        "streetVillageTown", "communityVillage", "streetRoad","streetNum","makeHole",
                        "holeDisposalResult","plaqueContent"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, enOpenHoleList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "开墙打洞信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();

            }
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-6 下午13:50:51
     * 类介绍  :   导入
     * 构造参数:
     *
     */
    public ToJson<EnOpenHole> importEnOpenHole(MultipartFile file, HttpServletResponse response,
                                               HttpServletRequest request, HttpSession session) {
        ToJson<EnOpenHole> json = new ToJson<>();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();

                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    EnOpenHole enOpenHole = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        enOpenHole = new EnOpenHole();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //是否符合“三有六无
                                            if ("是".equals(cell.getStringCellValue().trim())){
                                                enOpenHole.setComform("1");
                                            }else {
                                                enOpenHole.setComform("0");
                                            }
                                            break;
                                        case 1:
                                            //台账编号
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enOpenHole.setParameterNum(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //详细地址
                                            enOpenHole.setDetailAddress(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //行政区
                                            enOpenHole.setDistrict(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //街乡镇
                                            enOpenHole.setStreetVillageTown(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //社区村
                                            enOpenHole.setCommunityVillage(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //所属街路
                                            enOpenHole.setStreetRoad(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            //具体街道号码
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enOpenHole.setStreetNum(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //是否开墙打洞
                                            if ("是".equals(cell.getStringCellValue().trim())){
                                                enOpenHole.setMakeHole("1");
                                            }else {
                                                enOpenHole.setMakeHole("0");
                                            }
                                            break;
                                        case 9:
                                            //开墙打洞处置结果
                                            if ("房屋拆迁".equals(cell.getStringCellValue())){
                                                enOpenHole.setHoleDisposalResult("1");
                                            }else if ("恢复原状".equals(cell.getStringCellValue())){
                                                enOpenHole.setHoleDisposalResult("2");
                                            }else {
                                                enOpenHole.setHoleDisposalResult("");
                                            }
                                            break;
                                        case 10:
                                            //牌匾内容
                                            enOpenHole.setPlaqueContent(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            //位置坐标
                                            enOpenHole.setS1(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            enOpenHole.setCreateUser(users.getUserId());
                            enOpenHole.setCreateTime(DateFormat.getCurrentTime());
                            //将数据放入数据库
                            int count=enOpenHoleMapper.insertSelective(enOpenHole);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                json.setTotleNum(successCount);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setTotleNum(successCount+1);
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }

}
